﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XiaoGang.Soft.XGWMS.COM;
using Excel;
using System.IO;
using System.Reflection;

namespace XiaoGang.Soft.XGWMS.UI
{
    public partial class M009_Sales_Detail : FormBase
    {
        public M009_Sales_Detail()
        {
            InitializeComponent();
        }

        #region 变量定义

        BLL.BLL_M012_MEMBER bll_M012_Member = new XiaoGang.Soft.XGWMS.BLL.BLL_M012_MEMBER();
        private const string dataName = "销售明细";
       
        #endregion

        #region 方法

        protected void SetTableIndex()
        {
            int intIndex = 0;
            groupBox1.TabIndex = intIndex; intIndex++;
            dtpDateFrom.TabIndex = intIndex; intIndex++;
            dateDateTo.TabIndex = intIndex; intIndex++;
            ckbDetail.TabIndex = intIndex; intIndex++;
            btnSearch.TabIndex = intIndex; intIndex++;
            grpBillDetailInfo.TabIndex = intIndex; intIndex++;
            btnPrint.TabIndex = intIndex; intIndex++;
            btnClose.TabIndex = intIndex; intIndex++;
        }

        /// <summary>
        /// <p><b>方法名称</b>InitialGridView</p>
        /// <p><b>概要説明	:</b>Grid初始化</p>
        /// <p><b>作成者	:</b>万岗</p>
        /// <p><b>作成日	:</b>2008/09/10</p>
        /// </summary>
        protected void InitialGridView()
        {
            grdmentBillDetailInfo.Height = 382;
            grdmentBillDetailInfo.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Raised;
            grdmentBillDetailInfo.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grdmentBillDetailInfo.ReadOnly = true;
            grdmentBillDetailInfo.ColumnHeadersHeight = 20;
            grdmentBillDetailInfo.ColumnHeadersVisible = true;
            grdmentBillDetailInfo.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            grdmentBillDetailInfo.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            grdmentBillDetailInfo.Columns.Add("NO.", "NO.");
            grdmentBillDetailInfo.Columns.Add("BUSINESS_TIME", "日期");
            grdmentBillDetailInfo.Columns.Add("BILL_ID", "流水号");
            grdmentBillDetailInfo.Columns.Add("GOODS_NM1", "商品名称");
            grdmentBillDetailInfo.Columns.Add("SELLING_PRICE", "价格");
            grdmentBillDetailInfo.Columns.Add("UNITS", "数量");
            grdmentBillDetailInfo.Columns.Add("AllPrice", "合计");            
            grdmentBillDetailInfo.Columns.Add("Preferential", "优惠");
            grdmentBillDetailInfo.Columns.Add("BillCount", "本单合计");
            grdmentBillDetailInfo.Columns.Add("USER_NAME", "会员");
            grdmentBillDetailInfo.Columns.Add("DateTotal", "日合计");
            grdmentBillDetailInfo.Columns.Add("MonthTotal", "月合计");
            grdmentBillDetailInfo.Columns.Add("USER_NO", "会员卡号");

            grdmentBillDetailInfo.Columns["NO."].Width = 29;
            grdmentBillDetailInfo.Columns["NO."].Frozen = true;
            grdmentBillDetailInfo.Columns["NO."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdmentBillDetailInfo.Columns["NO."].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["NO."].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["BUSINESS_TIME"].Width = 68;
            grdmentBillDetailInfo.Columns["BUSINESS_TIME"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdmentBillDetailInfo.Columns["BUSINESS_TIME"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["BUSINESS_TIME"].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["BILL_ID"].Width = 80;
            grdmentBillDetailInfo.Columns["BILL_ID"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["BILL_ID"].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["GOODS_NM1"].Width = 180;
            grdmentBillDetailInfo.Columns["GOODS_NM1"].Frozen = true;            
            grdmentBillDetailInfo.Columns["GOODS_NM1"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["SELLING_PRICE"].Width = 50;
            grdmentBillDetailInfo.Columns["SELLING_PRICE"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["SELLING_PRICE"].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["SELLING_PRICE"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["UNITS"].Width = 35;
            grdmentBillDetailInfo.Columns["UNITS"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["UNITS"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["UNITS"].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["AllPrice"].Width = 55;
            grdmentBillDetailInfo.Columns["AllPrice"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["AllPrice"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["AllPrice"].Resizable = DataGridViewTriState.False;

            grdmentBillDetailInfo.Columns["BillCount"].Width = 55;
            grdmentBillDetailInfo.Columns["BillCount"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["BillCount"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["BillCount"].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["Preferential"].Width =50;
            grdmentBillDetailInfo.Columns["Preferential"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["Preferential"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["Preferential"].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["USER_NAME"].Width = 50;
            grdmentBillDetailInfo.Columns["USER_NAME"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["USER_NAME"].Resizable = DataGridViewTriState.False;

            grdmentBillDetailInfo.Columns["DateTotal"].Width = 55;
            grdmentBillDetailInfo.Columns["DateTotal"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["DateTotal"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["DateTotal"].Resizable = DataGridViewTriState.False;

            grdmentBillDetailInfo.Columns["MonthTotal"].Width = 55;
            grdmentBillDetailInfo.Columns["MonthTotal"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["MonthTotal"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["MonthTotal"].Resizable = DataGridViewTriState.False;

            grdmentBillDetailInfo.Columns["USER_NO"].Width = 72;
            grdmentBillDetailInfo.Columns["USER_NO"].SortMode = DataGridViewColumnSortMode.NotSortable;
            grdmentBillDetailInfo.Columns["USER_NO"].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["USER_NO"].Visible = false;
            grdmentBillDetailInfo.AllowUserToAddRows = false;
            grdmentBillDetailInfo.AllowUserToResizeColumns = true;
            grdmentBillDetailInfo.AllowUserToResizeRows = false;
            grdmentBillDetailInfo.RowHeadersVisible = false;
            grdmentBillDetailInfo.RowTemplate.Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.RowTemplate.Height = 20;
            grdmentBillDetailInfo.RowTemplate.ReadOnly = true;
        }

        /// <summary>
        /// <p><b>方法名称</b>InitProcess</p>
        /// <p><b>概要説明	:</b>画面的初期化</p>
        /// <p><b>作成者	:</b>万岗</p>
        /// <p><b>作成日	:</b>2008/09/10</p>
        /// </summary>
        protected void InitProcess()
        {
            InitialGridView();
            SetTableIndex();
            InitContranls();
            ShowGrid();
        }

        protected void InitContranls()
        {
            dtpDateFrom.Text = DateTime.Now.ToString("yyyy-MM-dd");
            dateDateTo.Text = DateTime.Now.ToString("yyyy-MM-dd");
            lbTatle.Text = "";
            ckbDetail.Checked = true;
        }

        /// <summary>
        /// 
        /// </summary>
        protected void ShowGrid()
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Cursor = Cursors.WaitCursor;

            ReturnValue rvGoods;

            string strDateFrom = dtpDateFrom.Text.Trim().Replace("-", "").Replace("/", "");
            string strDateTo = dateDateTo.Text.Trim().Replace("-", "").Replace("/", "");
            if (ckbDetail.Checked)
            {
                //以详细显示
                rvGoods = bll_M012_Member.GetSalesDetail(strDateFrom, strDateTo);
            }
            else
            {
                //以每单显示
                rvGoods = bll_M012_Member.GetBillTotalPrice(strDateFrom, strDateTo);
            }            
            if (rvGoods.IsSuccess == false)
            {
                Method.MessageShow(rvGoods.ErrorID,dataName);
                this.Cursor = Cursors.Default;
                return;
            }
            grdmentBillDetailInfo.Rows.Clear();
            //decimal TotalSales = 0m;
            
            if (ckbDetail.Checked)
            {
                //以详细显示
                foreach (DataRow row in rvGoods.ResultDataSet.Tables[0].Rows)
                {                    
                    grdmentBillDetailInfo.Rows.Add(
                        (grdmentBillDetailInfo.Rows.Count + 1).ToString(),
                        DateFormat(row["BUSINESS_TIME"].ToString().Trim()),
                        row["BILL_ID"].ToString().Trim(),
                        row["GOODS_NM1"].ToString().Trim(),
                        row["SELLING_PRICE"].ToString().Trim() == "-1.0000" ? "" : string.Format("{0:f2}", decimal.Parse(row["SELLING_PRICE"].ToString().Trim())),
                        row["UNITS"].ToString().Trim(),
                        row["SELLING_PRICE"].ToString().Trim() == "-1.0000" ? "" : string.Format("{0:f2}", decimal.Parse(row["AllPrice"].ToString().Trim())),
                        row["Preferential"].ToString().Trim() == "" ? "" : string.Format("{0:f2}", decimal.Parse(row["Preferential"].ToString().Trim())),
                        row["BillCount"].ToString().Trim() == "" ? "" : string.Format("{0:f2}", decimal.Parse(row["BillCount"].ToString().Trim())),
                        row["USER_NAME"].ToString().Trim(),
                        "",
                        "",
                        row["USER_NO"].ToString().Trim());
                    //TotalSales += decimal.Parse(row["AllPrice"].ToString().Trim());
                }
            }
            else
            {
                foreach (DataRow row in rvGoods.ResultDataSet.Tables[0].Rows)
                {
                    grdmentBillDetailInfo.Rows.Add(
                        (grdmentBillDetailInfo.Rows.Count + 1).ToString(),
                        DateFormat(row["BUSINESS_TIME"].ToString().Trim()),
                        row["BILL_ID"].ToString().Trim(),
                        row["GOODS_NM1"].ToString().Trim(),
                        row["SELLING_PRICE"].ToString().Trim(),
                        row["UNITS"].ToString().Trim(),
                        row["SELLING_PRICE"].ToString().Trim(),                        
                        row["Preferential"].ToString().Trim() == "" ? "" : string.Format("{0:f2}", decimal.Parse(row["Preferential"].ToString().Trim())),
                        row["BillCount"].ToString().Trim() == "" ? "" : string.Format("{0:f2}", decimal.Parse(row["BillCount"].ToString().Trim())-(row["Preferential"].ToString().Trim() == "" ? 0 : decimal.Parse(row["Preferential"].ToString().Trim()))),
                        row["USER_NAME"].ToString().Trim(),
                        "",
                        "",
                        row["USER_NO"].ToString().Trim());
                    //TotalSales += decimal.Parse(row["BillCount"].ToString().Trim() == "" ? "0" : row["BillCount"].ToString().Trim());
                }
            }
            if (grdmentBillDetailInfo.Rows.Count > 17)
            {
                grdmentBillDetailInfo.Columns["GOODS_NM1"].Width = 153;
            }
            else
            {
                grdmentBillDetailInfo.Columns["GOODS_NM1"].Width = 170;
            }
            //清除重复数据
            ClearGridRepeatData();
            //计算日销售额，月销售额
            SetDateMonthGridRepeatData();
            //清除日、月销售额重复数据
            ClearDateMonthGridRepeatData();
            //计算总销售额
            SetTotalGridRepeatData();
            //lbTatle.Text = "销售总额:" + string.Format("{0:f2}", TotalSales);// +"  共有" + grdmentBillDetailInfo.Rows.Count + "条销售记录";
            //grpBillDetailInfo.Text = "销售总额:" + string.Format("{0:f2}",TotalSales) + "  共有" + grdmentBillDetailInfo.Rows.Count + "条销售记录";
            //SetGridBackColor();
            this.Cursor = Cursors.Default;
        }

        /// <summary>	
        /// <p><b>方法名称</b>DateFormat</p>	
        /// <p><b>概要説明  :</b>date data format</p>	
        /// <p><b>作成者	:</b>万岗</p>	
        /// <p><b>作成日	:</b>2008/09/10</p>	
        /// <p><b>修改历史  :</b></p>	
        /// </summary>
        /// <param name="strValue">没有格式化的字符串</param> 
        /// <returns type="string">格式化后的字符串</returns>
        protected string DateFormat(string strValue)
        {
            if (strValue.Length < 8)
            {
                return strValue;
            }
            return strValue.Substring(0, 4) + "/" +
                strValue.Substring(4, 2) + "/" +
                strValue.Substring(6, 2);

        }

        /// <summary>	
        /// <p><b>方法名称</b>NumPriceFormat</p>	
        /// <p><b>概要説明  :</b>num and price data format</p>	
        /// <p><b>作成者	:</b>万岗</p>	
        /// <p><b>作成日	:</b>2008/09/10</p>	
        /// <p><b>修改历史:</b></p>	
        /// </summary>
        /// <param name="strValue">没有格式化的字符串</param> 
        /// <returns type="string">格式化后的字符串</returns>
        protected string NumPriceFormat(string strValue)
        {
            string strTemp = strValue;
            if (strValue.Length > 6)
            {
                strTemp = strValue.Substring(0, strValue.Length - 6) + ","
                    + strValue.Substring((strValue.Substring(0, strValue.Length - 6)).Length, 3)
                    + "," + strValue.Substring(strValue.Length - 3, 3);

            }
            else if (strValue.Length > 3)
            {
                strTemp = strValue.Substring(0, strValue.Length - 3) + ","
                + strValue.Substring((strValue.Substring(0, strValue.Length - 3)).Length, 3);
            }
            return strTemp;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="myExcel"></param>
        /// <param name="dsData"></param>
        private void WriteExlWithDataTable(Excel.Application myExcel, DataSet dsData)
        {
            Excel.Workbook myBook = myExcel.Workbooks[1];
            Excel.Worksheet mySheet = (Excel.Worksheet)myBook.Worksheets[1];
            Excel.Range r;
            Excel.Range r1;
            for (int i = 0; i < dsData.Tables[0].Rows.Count; i++)
            {
                r = (Excel.Range)mySheet.Rows.get_Item(i + 6, Missing.Value);
                r.Copy(Missing.Value);
                r1 = (Excel.Range)mySheet.Rows.get_Item(i + 7, Missing.Value);
                r1.PasteSpecial(XlPasteType.xlPasteFormats, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
                myExcel.Cells[i + 6, 1] = "'" + (i + 1).ToString();
                myExcel.Cells[i + 6, 2] = "'" + dsData.Tables[0].Rows[i]["GOODS_ID"].ToString();
                //myExcel.Cells[i + 6, 3] = "'" + dsData.Tables[0].Rows[i]["GOODS_NO"].ToString();
                myExcel.Cells[i + 6, 3] = "'" + dsData.Tables[0].Rows[i]["GOODS_NM1"].ToString();
                myExcel.Cells[i + 6, 4] = "'" + dsData.Tables[0].Rows[i]["GOODS_NM2"].ToString();
                myExcel.Cells[i + 6, 5] = "'" + dsData.Tables[0].Rows[i]["GOODS_GROUP"].ToString();
                myExcel.Cells[i + 6, 6] = "'" + dsData.Tables[0].Rows[i]["PROVIDER"].ToString();
                myExcel.Cells[i + 6, 7] = "'" + dsData.Tables[0].Rows[i]["PRODUCE_DATE"].ToString();
                myExcel.Cells[i + 6, 8] = "'" + dsData.Tables[0].Rows[i]["OVER_PRODUCE_DATE"].ToString();
                //myExcel.Cells[i + 6, 10] = "'" + dsData.Tables[0].Rows[i]["OVER_DATE"].ToString();
                //myExcel.Cells[i + 6, 11] = "'" + dsData.Tables[0].Rows[i]["MAX_WARN"].ToString();
                //myExcel.Cells[i + 6, 12] = "'" + dsData.Tables[0].Rows[i]["MIN_WARN"].ToString();
                myExcel.Cells[i + 6, 9] = "'" + dsData.Tables[0].Rows[i]["BUYING_PRICE"].ToString();
                myExcel.Cells[i + 6, 10] = "'" + dsData.Tables[0].Rows[i]["SELLING_PRICE"].ToString();
                //myExcel.Cells[i + 6, 15] = "'" + dsData.Tables[0].Rows[i]["MEMO"].ToString();
            }
        }

        /// <summary>
        /// SaveFile
        /// </summary>
        /// <param name="strMobanName"></param>
        /// <param name="filename"></param>
        private void SaveFile(string strMobanName, out string filename)
        {
            SaveFileDialog mySave = new SaveFileDialog();
            mySave.Filter = "Excelﾎﾄｼ(*.XLS)|*.xls|ﾋﾐﾎﾄｼ(*.*)|*.*";
            if (mySave.ShowDialog() != DialogResult.OK)
            {
                filename = null;
                return;
            }
            else
            {
                filename = mySave.FileName;
                string filenameold = mySave.FileName;
                FileInfo mode = new FileInfo(System.Windows.Forms.Application.StartupPath.Trim() + "\\" + strMobanName);
                try
                {
                    mode.CopyTo(filename, true);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                    return;
                }
            }
        }

        /// <summary>
        /// 设置不同流水号的销售信息不同背景色
        /// </summary>
        private void SetGridBackColor()
        {
            string strBillID = string.Empty;
            Color bkColor2=Color.Snow;
            for (int i = 0; i < grdmentBillDetailInfo.Rows.Count; i++)
            {
                if (i != 0 && grdmentBillDetailInfo.Rows[i].Cells["BILL_ID"].Value.ToString().Trim() != strBillID)
                {
                    if (bkColor2 == Color.Snow)
                    {
                        bkColor2=Color.PowderBlue;
                    }
                    else
                    {
                        bkColor2 = Color.Snow;
                    }
                }
                grdmentBillDetailInfo.Rows[i].DefaultCellStyle.BackColor = bkColor2;
                strBillID = grdmentBillDetailInfo.Rows[i].Cells["BILL_ID"].Value.ToString().Trim();
            }
        }

        /// <summary>
        /// 清除Grid中的重複數據
        /// </summary>
        private void ClearGridRepeatData()
        {
            string strBillID = string.Empty;
            int intNO = 1;
            for (int i = 0; i < grdmentBillDetailInfo.Rows.Count; i++)
            {
                if (i == 0)
                {
                    strBillID = grdmentBillDetailInfo.Rows[i].Cells["BILL_ID"].Value.ToString().Trim();
                }
                if (i != 0 && grdmentBillDetailInfo.Rows[i].Cells["BILL_ID"].Value.ToString().Trim() == strBillID)
                {
                    grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value = "";
                    grdmentBillDetailInfo.Rows[i].Cells["BILL_ID"].Value = "";
                    grdmentBillDetailInfo.Rows[i].Cells["NO."].Value = "";
                }
                else
                {                    
                    grdmentBillDetailInfo.Rows[i].Cells["NO."].Value = intNO;
                    strBillID = grdmentBillDetailInfo.Rows[i].Cells["BILL_ID"].Value.ToString().Trim();
                    intNO++;
                }

                if (i + 1 < grdmentBillDetailInfo.Rows.Count)
                {
                    if (grdmentBillDetailInfo.Rows[i + 1].Cells["BILL_ID"].Value.ToString().Trim() == strBillID)
                    {
                        grdmentBillDetailInfo.Rows[i].Cells["Preferential"].Value = "";
                        grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value = "";
                        grdmentBillDetailInfo.Rows[i].Cells["USER_NAME"].Value = "";
                        grdmentBillDetailInfo.Rows[i].Cells["USER_NO"].Value = "";
                    }
                }
            }
        }

        /// <summary>
        /// 清除Grid中的日合计、月合计重複數據
        /// </summary>
        private void ClearDateMonthGridRepeatData()
        {
            string strDate = string.Empty;
            string strMonth= string.Empty;
            for (int i = 0; i < grdmentBillDetailInfo.Rows.Count; i++)
            {
                if (i == 0)
                {
                    strDate = grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim();
                    strMonth = grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim().Substring(0,7);
                }                

                if (grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim() != "")
                {
                    if (i != 0 && grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim() != strDate)
                    {
                        strDate = grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim();
                    }

                    if (i != 0 && grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim().Substring(0, 7) != strMonth)
                    {
                        strMonth = grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim().Substring(0, 7);
                    }
                }

                if (i + 1 < grdmentBillDetailInfo.Rows.Count)
                {
                    if (grdmentBillDetailInfo.Rows[i + 1].Cells["BUSINESS_TIME"].Value.ToString().Trim() =="" 
                        || grdmentBillDetailInfo.Rows[i + 1].Cells["BUSINESS_TIME"].Value.ToString().Trim() == strDate)
                    {
                        grdmentBillDetailInfo.Rows[i].Cells["DateTotal"].Value = "";
                    }
                    if (grdmentBillDetailInfo.Rows[i + 1].Cells["BUSINESS_TIME"].Value.ToString().Trim()=="" 
                        || grdmentBillDetailInfo.Rows[i + 1].Cells["BUSINESS_TIME"].Value.ToString().Trim().Substring(0, 7) == strMonth)
                    {
                        grdmentBillDetailInfo.Rows[i].Cells["MonthTotal"].Value = "";
                    }
                }
            }
        }

        /// <summary>
        /// 设置日、月合计
        /// </summary>
        private void SetDateMonthGridRepeatData()
        {
            string strDate = "";
            string strDateOld = "";
            string strMonth = "";
            string strMonthOld = "";
            decimal TotalDate = 0m;
            decimal TotalMonth = 0m;            
            for (int i = 0; i < grdmentBillDetailInfo.Rows.Count; i++)
            {
                //计算日合计                
                strDate = grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim();
                if (strDate != strDateOld && strDate!="")//新的一天
                {
                    TotalDate = grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim() == "" ? 0 : decimal.Parse(grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim());
                    grdmentBillDetailInfo.Rows[i].Cells["DateTotal"].Value = string.Format("{0:f2}", TotalDate);                    
                    strDateOld = strDate;
                }
                else//同一天
                {
                    TotalDate += grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim() == "" ? 0 : decimal.Parse(grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim());
                    grdmentBillDetailInfo.Rows[i].Cells["DateTotal"].Value = string.Format("{0:f2}", TotalDate);                        
                }

                //计算月合计
                if (grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString ().Trim ().Length > 7)
                {
                    strMonth = grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString ().Trim ().Substring (0, 7);
                }
                if (strMonth != strMonthOld && strMonth !="")
                {
                    TotalMonth = grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim() == "" ? 0 : decimal.Parse(grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim());
                    grdmentBillDetailInfo.Rows[i].Cells["MonthTotal"].Value = string.Format("{0:f2}", TotalMonth);                    
                    strMonthOld = strMonth;
                }
                else
                {
                    TotalMonth += grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim() == "" ? 0 : decimal.Parse(grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim());
                    grdmentBillDetailInfo.Rows[i].Cells["MonthTotal"].Value = string.Format("{0:f2}", TotalMonth);
                }
            }
        }

        /// <summary>
        /// 计算设置总计
        /// </summary>
        private void SetTotalGridRepeatData()
        {
            decimal TotalSales = 0m;
            for (int i = 0; i < grdmentBillDetailInfo.Rows.Count; i++)
            {
                //计算日合计
                if ("" != grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim())
                {
                    TotalSales += decimal.Parse(grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim());
                }
            }
            lbTatle.Text = "销售总额:" + string.Format("{0:f2}", TotalSales);
        }

        #endregion

        #region 事件

        private void M014_BILLSCAN_Detail_Load(object sender, EventArgs e)
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitProcess();
        }

        /// <summary>
        /// btnClose_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Close();
        }

        /// <summary>
        /// btnPrint_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (grdmentBillDetailInfo.Rows.Count < 1)
            {
                Method.MessageShow("W11049","");//没有数据！
                return;
            }
            Print();
        }

        /// <summary>
        /// 打印销售记录
        /// </summary>
        private void Print()
        {
            //每次生成Excel前强制进行垃圾回收
            GC.Collect();
            if (Cursor.Current == Cursors.WaitCursor)
            {
                return;
            }
            if (Method.MessageShow("Q12014",dataName) == DialogResult.Yes)//确定要进行打印吗？
            {                
                //创建一个Excel文件  
                object missing = Missing.Value;
                Excel.Application appExcel = new Excel.Application();
                Excel.Workbooks myBooks = appExcel.Workbooks;
                //工作薄是否可见
                appExcel.Visible = false;
                //向Excel中添加一个工作薄
                Excel._Workbook workbook = myBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
                //向工作薄中添加一个Sheet
                Excel.Worksheet mySheet = (Excel.Worksheet)workbook.Worksheets.Add(Missing.Value, Missing.Value, 1, Missing.Value);
                //使某个Sheet作为当前选择项
                ((Excel.Worksheet)appExcel.ActiveWorkbook.Sheets[1]).Select(Missing.Value);

                //myExcel.Application.Workbooks.Add(true); 
                //第一行为报表名称  
                mySheet.get_Range("A1", Missing.Value).Value2 = "销售记录";
                //这是单元格居中对齐
                mySheet.get_Range("A1", Missing.Value).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
                //这是行高
                mySheet.get_Range("A1", Missing.Value).RowHeight = 30;
                //设置字体
                mySheet.get_Range("A1", Missing.Value).Font.Bold = true;
                mySheet.get_Range("A1", Missing.Value).Font.Size = 15;
                //设置整个报表的标题为跨列居中
                //mySheet.get_Range("A1", Missing.Value).HorizontalAlignment = xlHAlignCenterAcrossSelection;
                //合并单元格
                mySheet.get_Range(appExcel.Cells[1, 1], appExcel.Cells[1, 9]).Merge(false);

                //NO.、日期、流水号、商品名称、价格、数量、合计、本单合计、优惠、会员姓名、会员卡号
                //NO.、BUSINESS_TIME、BILL_ID、GOODS_NM1、SELLING_PRICE、UNITS、AllPrice、BillCount、Preferential、USER_NAME、USER_NO
                appExcel.Cells[2, 1] = "日期";
                mySheet.get_Range("A2", Missing.Value).ColumnWidth = 8;
                mySheet.get_Range("A2", Missing.Value).Font.Bold = true;
                appExcel.Cells[2, 2] = "流水号";
                mySheet.get_Range("B2", Missing.Value).ColumnWidth = 11;
                mySheet.get_Range("B2", Missing.Value).Font.Bold = true;
                appExcel.Cells[2, 3] = "'商品名称";
                mySheet.get_Range("C2", Missing.Value).ColumnWidth = 26;
                mySheet.get_Range("C2", Missing.Value).Font.Bold = true;
                appExcel.Cells[2, 4] = "'单价";
                mySheet.get_Range("D2", Missing.Value).ColumnWidth = 5;
                mySheet.get_Range("D2", Missing.Value).Font.Bold = true;
                appExcel.Cells[2, 5] = "'数量";
                mySheet.get_Range("E2", Missing.Value).ColumnWidth = 4;
                mySheet.get_Range("E2", Missing.Value).Font.Bold = true;
                appExcel.Cells[2, 6] = "'合计";
                mySheet.get_Range("F2", Missing.Value).ColumnWidth =6;
                mySheet.get_Range("F2", Missing.Value).Font.Bold = true;

                appExcel.Cells[2, 7] = "'总计";
                mySheet.get_Range("G2", Missing.Value).ColumnWidth = 6;
                mySheet.get_Range("G2", Missing.Value).Font.Bold = true;

                appExcel.Cells[2, 8] = "'优惠";
                mySheet.get_Range("H2", Missing.Value).ColumnWidth = 4;
                mySheet.get_Range("H2", Missing.Value).Font.Bold = true;

                appExcel.Cells[2, 9] = "'会员";
                mySheet.get_Range("I2", Missing.Value).ColumnWidth = 5;
                mySheet.get_Range("I2", Missing.Value).Font.Bold = true;


                //逐行写入数据，  
                int intRow = 3;
                for (int i = 0; i < grdmentBillDetailInfo.Rows.Count; i++)
                {
                    //以单引号开头，表示该单元格为纯文本  
                    appExcel.Cells[intRow + i, 1] = grdmentBillDetailInfo.Rows[i].Cells["BUSINESS_TIME"].Value.ToString().Trim();//日期
                    appExcel.Cells[intRow + i, 2] = "'"+grdmentBillDetailInfo.Rows[i].Cells["BILL_ID"].Value.ToString().Trim();//流水号
                    appExcel.Cells[intRow + i, 3] = grdmentBillDetailInfo.Rows[i].Cells["GOODS_NM1"].Value.ToString().Trim();//商品名称
                    appExcel.Cells[intRow + i, 4] = grdmentBillDetailInfo.Rows[i].Cells["SELLING_PRICE"].Value.ToString().Trim();//价格
                    appExcel.Cells[intRow + i, 5] = grdmentBillDetailInfo.Rows[i].Cells["UNITS"].Value.ToString().Trim();//数量
                    appExcel.Cells[intRow + i, 6] = grdmentBillDetailInfo.Rows[i].Cells["AllPrice"].Value.ToString().Trim();//合计
                    appExcel.Cells[intRow + i, 7] = grdmentBillDetailInfo.Rows[i].Cells["BillCount"].Value.ToString().Trim();//本单合计
                    appExcel.Cells[intRow + i, 8] = grdmentBillDetailInfo.Rows[i].Cells["Preferential"].Value.ToString().Trim();//优惠
                    appExcel.Cells[intRow + i, 9] = grdmentBillDetailInfo.Rows[i].Cells["USER_NAME"].Value.ToString().Trim();//会员
                }
                mySheet.get_Range("A3", "I" + (grdmentBillDetailInfo.Rows.Count + 2).ToString()).Font.Size = 10;
                //让Excel文件可见
                //工作薄是否可见
                appExcel.Visible = true;
            }
        }

        /// <summary>
        /// M014_BILLSCAN_Detail_KeyUp
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void M014_BILLSCAN_Detail_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F5:
                    btnPrint_Click(sender, e);
                    break;
                case Keys.Escape:
                    btnClose_Click(sender, e);
                    break;
            }
        }

        #endregion

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ShowGrid();
        }

        /// <summary>
        /// 显示详细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckbDetail_CheckedChanged(object sender, EventArgs e)
        {
            ShowGrid();
        }
    }
}